package interviewClassic150;

import org.junit.Test;

public class GameOfLife {
    public void gameOfLife(int[][] board) {
        //引入特殊状态
        //board[i][j] = 2 代表之前是活的，现在是死的
        //board[i][j] = 3 代表之前是死的，现在是活的
        //八个方向
        int[][] dir = {{-1,0},{-1,-1},{0,-1},{1,-1},{1,0},{1,1},{0,1},{-1,1}};

        int m = board.length;
        int n = board[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int cur = board[i][j];//当前细胞状态
                int liveCount = 0;//八个方向的活细胞的数量
                for (int k = 0; k < 8; k++) {
                    int nextI = i + dir[k][0];
                    int nextJ = j + dir[k][1];
                    if (nextI >= 0 && nextI < m && nextJ >= 0 && nextJ < n) {
                        //下一个方向合理
                        if (board[nextI][nextJ] == 2 || board[nextI][nextJ] == 1) liveCount++;
                    }
                }
                //八个方向遍历完了，判断
                if (board[i][j] == 1 && liveCount < 2) board[i][j] = 2;
                else if (board[i][j] == 1 && liveCount == 2 && liveCount == 3) board[i][j] = 1;
                else if (board[i][j] == 1 && liveCount > 3) board[i][j] = 2;
                else if (board[i][j] == 0 && liveCount == 3) board[i][j] = 3;
            }
        }

        //重置状态
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == 2) board[i][j] = 0;
                else if (board[i][j] == 3) board[i][j] = 1;
            }
        }
    }

    @Test
    public void test() {
        int[][] board = {{0,1,0},{0,0,1},{1,1,1},{0,0,0}};
        gameOfLife(board);
        System.out.println(board);
    }
}
